import React from 'react';
import { Modal, message, Tabs, Empty, Button } from 'antd';
import cass from 'classnames';
import s from './index.module.less';
import projectServer from '../../services/project';
import taskServer from '../../services/task';
import SearchInput from '../SearchInput';
import TaskItem from '../TaskItem';
import isSuccess from '../../utils/error';
import CustomModal from './CustomModal';
import debounce from 'lodash/debounce';
import { netCheckFn } from '../../utils/netCheck';

const { forUploadTaskList: getTaskList } = taskServer;
const { linkProjectList: getProjectList, getFolderlist } = projectServer;

const TabPane = Tabs.TabPane;
const typeConfig = {
  1: { label: '民' },
  2: { label: '刑' },
  3: { label: '法' },
  4: { label: '专' },
};

class PickerModal extends React.Component {
  static defaultProps = {
    needReflesh: 'false', // 用于项目模块添加自定义文件夹后刷新文件夹列表
  };

  constructor(props) {
    super(props);
    this.state = {
      type: props.type || 1,
      projectList: [],
      taskList: [],
      folderlist: [],
      leftActiveIndex: '',
      rightActiveIndex: '',
    };
  }

  componentWillMount() {
    const { hiddenTask } = this.props;
    // 请求所有项目和任务列表
    this.getProjectList();
    if (!hiddenTask) this.getTaskList();
  }

  componentWillReceiveProps(nextProps) {
    if (this.props.needReflesh !== nextProps.needReflesh) {
      this.getProjectList();
      if (!nextProps.hiddenTask) this.getTaskList();
    } else if (nextProps.visible && (nextProps.taskid || nextProps.projectid)) {
      this.setState({ type: nextProps.type });
      if (nextProps.type == '1') {
        this.positionProject(this.state.projectList);
      } else if (!nextProps.hiddenTask && nextProps.type == '2') {
        this.positionTask(this.state.taskList);
      }
    }
  }

  getProjectList = async (params) => {
    // const res = await getProjectList(params);
    let searchkey = params && params.searchkey || '';
    let res = await netCheckFn('getProjectList-' + searchkey,async ()=>{
        const res = await getProjectList(params);
        return res;
    })
    if (isSuccess(res) && res.data) {
      // 初始化默认数据
      const { type, projectid } = this.props;
      if (!params && type == '1' && projectid && res.data.length) {
        this.positionProject(res.data);
      } else {
        this.setState({ projectList: res.data || [] });
      }
    }
  };

  positionProject = debounce(
    (projectList) => {
      const { projectid, projecttype, stageid } = this.props;
      const pi = projectList.findIndex((v) => v.recid === projectid);

      if (pi >= 0) {
        const si = projectList[pi].stages.findIndex((v) => v.stageid === stageid);
        if (si >= 0) {
          this.getFolderlist({ projectid, projecttype, stageid });
        }
        const indexData = projectList.splice(pi, 1)
        console.log(pi,projectid, si, stageid, indexData);
        this.setState({ leftActiveIndex: `${0}-${si >= 0 ? si : 0}`, projectList: [...indexData, ...projectList] });
      }
    },
    600,
    { leading: true }
  );

  getTaskList = async (params) => {
    // const res = await getTaskList(params);
    let searchkey = params && params.searchkey || '';
    let res = await netCheckFn('getTaskList-' + searchkey,async ()=>{
        const res = await getTaskList(params);
        return res;
    })
    if (isSuccess(res) && res.data) {
      // 初始化默认数据
      const { type, taskid } = this.props;
      if (!params && type == '2' && taskid && res.data.length) {
        this.positionTask(res.data);
      } else {
        this.setState({ taskList: res.data || [] });
      }
    }
  };

  positionTask = debounce(
    (taskList) => {
      const { taskid, type } = this.props;
      console.log('-------------------------taskid----------------------------');
      console.log(taskid, type);
      const ti = taskList.findIndex((v) => v?.recid === taskid);
      const indexData = taskList.splice(ti, 1);;
      this.setState({ leftActiveIndex: 0, taskList: [...indexData, ...taskList] });
    },
    600,
    { leading: true }
  );

  getFolderlist = async (params) => {
    const res = await getFolderlist(params);
    if (isSuccess(res)) {
      // console.log('---UploadModal getFolderlist---', res);
      this.setState({ folderlist: res.data || [] });
    }
  };

  handleCancel = () => {
    this.setState({ type: this.props.type, rightActiveIndex: '' });
    // 恢复默认
    const { hiddenTask } = this.props;
    this.getProjectList();
    if (!hiddenTask) this.getTaskList();
    this.props.onCancel();
  };

  handleOk = () => {
    const { leftActiveIndex, rightActiveIndex, type } = this.state;
    if (type == '1' && !rightActiveIndex && rightActiveIndex !== 0) {
      message.warn('请选择文件夹');
      return;
    }
    if (type == '2' && !leftActiveIndex && leftActiveIndex !== 0 && leftActiveIndex !== '-') {
      message.warn('请选择任务');
      return;
    }
    let returnObj = {};
    if (type == '1') {
      const [pathValue, p, s, f] = this.getPathValue(type);
      returnObj = { project: p, stage: s, folder: f, pathValue, type };
    } else if (type == '2') {
      const [pathValue, t] = this.getPathValue(type);
      returnObj = { task: t, pathValue, type };
    }
    this.setState({ rightActiveIndex: '' });
    this.props.onOk(returnObj, this.handleCancel);
  };

  getPathValue = (type) => {
    const { hiddenTask } = this.props;
    const { projectList, taskList, folderlist, leftActiveIndex, rightActiveIndex } = this.state;
    let value = [''];

    if (
      (!leftActiveIndex && leftActiveIndex !== 0) ||
      (type == '1' && !projectList.length) ||
      (type == '2' && !hiddenTask && !taskList.length)
    )
      return value;

    if (type == '1' && typeof leftActiveIndex === 'string') {
      const [pi, si] = leftActiveIndex.split('-');
      const p = projectList[pi];
      const s = projectList[pi]?.stages[si];
      // 项目名称-阶段名称-文件夹名称
      const pathValue = `[${s.stagename}] ${p.recname}`;
      value = [pathValue, p, s];
      if ((rightActiveIndex || rightActiveIndex === 0) && folderlist.length) {
        const f = folderlist[rightActiveIndex];
        value[0] = `${f.foldername}-${value[0]}`;
        value.push(f);
      }
    } else if (type == '2' && typeof leftActiveIndex === 'number') {
      // 任务名称
      const t = taskList[leftActiveIndex];
      if (t) {
        const pathValue = t.content;
        value = [pathValue, t];
      }
    }
    return value;
  };

  onTabsChange = (key) => {
    this.setState({ type: key });
  };

  onSearch = (v, type) => {
    if (type == '1') {
      this.getProjectList({ searchkey: v });
    } else if (type == '2') {
      this.getTaskList({ searchkey: v });
    }
    this.setState({ folderlist: [], leftActiveIndex: '' });
  };

  selectProject = (v, i) => {
    const idxs = i.split('-');
    this.getFolderlist({
      projectid: v.recid,
      projecttype: v.projecttype,
      stageid: v.stages[idxs[1]].stageid,
    });
    this.setState({ leftActiveIndex: i, rightActiveIndex: '' });
  };

  selectTask = (v, i) => {
    this.setState({ leftActiveIndex: i, rightActiveIndex: '' });
  };

  renderItem = (type, list) => {
    const { leftActiveIndex } = this.state;
    if (!list.length) {
      return (
        <div className={s.empty}>
          <Empty description={type == '1' ? '暂无项目' : '暂无任务'} />
        </div>
      );
    }
    if (type == '1') {
      return list.map((v, i) => (
        <div key={v.recid} className={s.wrapItem}>
          <div className={s.top}>
            <div>{typeConfig[v.projecttype].label}</div>
            <h3>{v.recname}</h3>
          </div>
          <div className={cass(s.bottom)}>
            {v.stages.map((d, idx) => (
              <div
                key={idx}
                onClick={() => this.selectProject(v, `${i}-${idx}`)}
                className={cass('hovergray', { [s.active]: leftActiveIndex === `${i}-${idx}` })}
                style={{ flex: 1, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}
              >
                <div className={s.itemName}>
                  {`[${d?.stagename}] 委托人：${d.clients.join(';')}`}
                  {d.host ? <span className={cass('mdi', 'mdi-flag')} key="flag" /> : null}
                </div>
                {leftActiveIndex === `${i}-${idx}` && (
                  <div className={s.check}>
                    <span className="mdi mdi-checkbox-marked-circle" />
                  </div>
                )}
              </div>
            ))}
          </div>
        </div>
      ));
    } else {
      return list.map((v, i) => (
        <TaskItem
          // unHoverable={true}
          className={s.taskWrap}
          key={`taskItem${i}`}
          data={v}
          active={leftActiveIndex === i}
          onClick={() => this.selectTask(v, i)}
        />
      ));
    }
  };

  onSelectFolder = (f, i) => {
    this.setState({ rightActiveIndex: i });
  };

  refleshFolder = ({ selProjectid, selProjecttype, selStageid }) => {
    this.getFolderlist({
      projectid: selProjectid,
      projecttype: selProjecttype,
      stageid: selStageid,
    });
  };

  getProductId = (type, leftActiveIndex, projectList) => {
    const returnData = {};
    if (type == '1' && leftActiveIndex && projectList.length && leftActiveIndex.split) {
      const [i, idx] = leftActiveIndex.split('-');
      returnData.selProjectid = projectList[i]?.recid;
      returnData.selProjecttype = projectList[i]?.projecttype;
      returnData.selStageid = projectList[i]?.stages[idx]?.stageid;
      returnData.inlawyermember = projectList[i]?.stages[idx]?.inlawyermember;
    }
    return returnData;
  };

  render() {
    const { visible, title, hiddenTask, showfooter } = this.props;
    const { type, projectList, taskList, folderlist, rightActiveIndex, leftActiveIndex, customModal } = this.state;
    if(!visible) return null;
    const tabs = [{ label: '项目', list: projectList, key: '1' }];

    if (!hiddenTask) tabs.push({ label: '任务', list: taskList, key: '2' });

    const pathValue = showfooter ? this.getPathValue(type)[0] : null;
    const idData = this.getProductId(type, leftActiveIndex, projectList);
    const { selProjectid, selStageid, inlawyermember } = idData;
    return (
      <Modal
        title={title}
        width={700}
        visible={visible}
        maskClosable={false}
        wrapClassName={s.wrapInnerModal}
        onCancel={() => this.handleCancel()}
        closable={false}
        footer={
          <div className={s.footBox}>
            {pathValue ? <div className={s.footer}>保存路径：{pathValue}</div> : null}
            <div>
              <Button onClick={this.handleCancel}>取消</Button>
              <Button type="primary" onClick={this.handleOk}>
                确定
              </Button>
            </div>
          </div>
        }
      >
        <div className={s.innerWrap}>
          <div className={s.left}>
            <Tabs activeKey={type} onChange={this.onTabsChange}>
              {tabs.map((d) => (
                <TabPane tab={d.label} key={d.key}>
                  <div>
                    <div className={s.search}>
                      <SearchInput
                        key={!visible ? Math.random() : 'search'}
                        placeholder="搜索"
                        onPressEnter={(v) => this.onSearch(v, type)}
                        onClear={() => this.onSearch('', type)}
                      />
                    </div>
                    <div className={s.listContent}>{this.renderItem(d.key, d.list)}</div>
                  </div>
                </TabPane>
              ))}
            </Tabs>
          </div>
          {type == '1' ? (
            <div className={s.right}>
              <div className={s.rightTitle}>
                选择文件夹
                <CustomModal
                  projectid={selProjectid}
                  stageid={selStageid}
                  show={customModal}
                  onSuccess={() => this.refleshFolder(idData)}
                  onCancel={() => this.setState({ customModal: false })}
                />
              </div>
              {folderlist.length ? (
                <div className={s.rightWrap}>
                  {folderlist.map((v, i) => (
                    <div
                      key={v.folderid}
                      className={cass(s.item, 'hovergray', { [s.active]: i === rightActiveIndex })}
                      onClick={() => this.onSelectFolder(v, i)}
                    >
                      {!v.lawyerfolder ? <span className={cass('mdi mdi-account', s.client)} /> : null}
                      {v.foldername}
                      <div className={s.logo}>
                        {i === rightActiveIndex ? (
                          <span className="mdi mdi-checkbox-marked-circle" />
                        ) : (
                          <span className="mdi mdi-checkbox-blank-circle-outline" />
                        )}
                      </div>
                    </div>
                  ))}
                  {inlawyermember ? (
                    <div className={cass(s.item, s.newItem, 'hovergray')} onClick={() => this.setState({ customModal: true })}>
                      <span className={cass('mdi mdi-plus', s.plus)} />
                      新建文件夹
                    </div>
                  ) : null}
                </div>
              ) : (
                <div className={s.empty}>
                  <Empty description={`该项目暂无文件夹，请先自定义文件夹`} />
                </div>
              )}
            </div>
          ) : null}
          {type == '2' ? (
            <div className={s.right}>
              <div className={s.rightTitle}>选择文件夹</div>
              <div className={s.empty}>
                <Empty description={'上传任务不需要选择文件夹，请直接确认'} />
              </div>
            </div>
          ) : null}
        </div>
      </Modal>
    );
  }
}

export default PickerModal;
